<template>
    <el-dialog :title="title" :visible.sync="dialogFormVisible" width="500px" @close="close">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
            <el-row :gutter="20">
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="警号" prop="user_name">
                        <el-input v-model.trim="form.user_name" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="姓名" prop="name">
                        <el-input v-model.trim="form.name" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="密码" v-if="form.id != null && form.id != '' && form.id != undefined">
                        <el-input v-model.trim="form.newPassword" type="password" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="密码" prop="pass" v-else>
                        <el-input v-model.trim="form.pass" type="password" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="部门" prop="dept_id">
                        <el-select class="main-select-tree w" ref="selectTree" v-model="form.deptName">
                            <el-option v-for="item in deptDatas" :key="item.value" :label="item.label"
                                :value="item.value" style="display: none;" />
                            <el-tree class="main-select-el-tree" ref="selecteltree" :data="deptDatas" node-key="id"
                                highlight-current :props="defaultProps" @node-click="handleNodeClick"
                                :current-node-key="form.dept_id" :expand-on-click-node="expandOnClickNode"
                                default-expand-all />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="角色"  style="text-align:left" prop="roleIdList">
                        <el-select multiple filterable  v-model.trim="form.roleIdList" class="w">
                            <el-option v-for="item in roleDatas" :key="item.id" :label="item.name" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                    <el-form-item label="手机号" prop="phone">
                        <el-input v-model.trim="form.phone" autocomplete="off"></el-input>
                    </el-form-item>
                </el-col>


              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="是否警令负责人"  class="labelEsp" style="text-align:left" prop="order_person">
                  <el-select filterable collapse-tags v-model.trim="form.order_person" class="w">
                    <el-option  key="0" label="是" value="0" />
                    <el-option  key="1" label="否" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
                <el-form-item label="是否警情负责人"  class="labelEsp" style="text-align:left" prop="situation_person">
                  <el-select filterable collapse-tags v-model.trim="form.situation_person" class="w">
                    <el-option  key="0" label="是" value="0" />
                    <el-option  key="1" label="否" value="1" />
                  </el-select>
                </el-form-item>
              </el-col>


            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="close">取 消</el-button>
            <el-button type="primary" @click="save" :loading="loading" :disabled="disabled">
                {{ loading? '确定中 ...': '确定' }}
            </el-button>
        </div>
    </el-dialog>
</template>

<script>
import { getUserById, doEdit } from '@/api/userManagement'
import { getDeptList } from '@/api/dept'
import { getRoleList } from '@/api/role'

export default {
    name: 'UserManagementEdit',
    data() {
        return {
            form: {
                id: '',
                user_name: '',
                pass: '',
                newPassword: '',
                name: '',
                dept_id: '',
                phone: '',
                roleIdList: [],
                order_person: '',
                situation_person: '',
            },
            rules: {
                user_name: [{ required: true, trigger: 'blur', message: '请输入用户名' },],
                pass: [{ required: true, trigger: 'blur', message: '请输入密码' }],
                name: [{ required: true, trigger: 'blur', message: '请输入姓名' }],
                dept_id: [{ required: true, trigger: 'blur', message: '请选择部门' }],
                order_person: [{ required: true, trigger: 'blur', message: '请选择是否为警令负责人' }],
                situation_person: [{ required: true, trigger: 'blur', message: '请选择是否为警情负责人' }],
                roleIdList: [{ required: true, trigger: 'blur', message: '请选择角色' }],
                // roleIds: [
                //     {required: true, trigger: 'blur', message: '请选择角色'},
                // ],
            },
            title: '',
            dialogFormVisible: false,
            value: 6,
            expandOnClickNode: true,
            options: [],
            datas: [{
                id: 1,
                label: '云南',
                children: [{
                    id: 2,
                    label: '昆明',
                    children: [
                        { id: 3, label: '五华区', children: [{ id: 8, label: '北辰小区' }] },
                        { id: 4, label: '盘龙区' }
                    ]
                }]
            }, {
                id: 5,
                label: '湖南',
                children: [
                    { id: 6, label: '长沙' },
                    { id: 7, label: '永州' }
                ]
            }],
            deptDatas: [],
            roleDatas: [],
            defaultProps: {
                children: 'children',
                label: 'label'
            },
            loading: false,
            disabled: false,
        }
    },
    created() {
    },
    methods: {
        async fetchData() {
            const { data } = await getUserById(this.form.id)
            // console.log(data)
            this.form = data.data
            this.form.order_person = data.data.order_person+"";
            this.form.situation_person = data.data.situation_person+"";
        },
        getDeptData() {
            getDeptList().then((res) => {
                // console.log("部门data：")
                // console.log(res.data)
                this.deptDatas = res.data
            })
        },
        getRoleData() {
            getRoleList().then((res) => {
                // console.log("角色data：")
                // console.log(res.data)
                this.roleDatas = res.data
            })
        },
        // 四级菜单
        formatData(data) {
            let options = [];
            data.forEach((item, key) => {
                options.push({ label: item.label, value: item.id });
                if (item.children) {
                    item.children.forEach((items, keys) => {
                        options.push({ label: items.label, value: items.id });
                        if (items.children) {
                            items.children.forEach((itemss, keyss) => {
                                options.push({ label: itemss.label, value: itemss.id });
                                if (itemss.children) {
                                    itemss.children.forEach((itemsss, keysss) => {
                                        options.push({ label: itemsss.label, value: itemsss.id });
                                    });
                                }
                            });
                        }
                    });
                }
            });
            return options;
        },
        handleNodeClick(node) {
            this.$set(this.form, "dept_id", node.id);
            this.$set(this.form, "deptName", node.name);
            this.$refs.selectTree.blur();
        },
        showEdit(row) {
            this.getDeptData()
            this.getRoleData()
            if (!row) {
                this.title = '添加'
            } else {
                this.title = '编辑'
                this.form.id = row;
                // this.form = Object.assign({}, row)
                this.fetchData()
            }
            this.dialogFormVisible = true
        },
        close() {
            this.$refs['form'].clearValidate()
            this.form = this.$options.data().form
            this.dialogFormVisible = false
        },
        save() {
            if (this.loading) {
                return
            }
            // if (this.form.roleIdList == null || this.form.roleIdList == "" || this.form.roleIdList == undefined || this.form.roleIdList.length == 0) {
            //     this.$baseMessage('请选择角色', 'error')
            //     return;
            // }
          var reg1 = /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[a-zA-Z0-9]{6,20}$/
          if (this.form.id != null && this.form.id != '' && this.form.id != undefined){
            if (this.form.newPassword != null && this.form.newPassword != '' && this.form.newPassword != undefined){
              if (!reg1.test(this.form.newPassword)){
                this.$baseMessage('密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 6-20 之间', 'error');
                return;
              }
            }
          }else {
            if (this.form.pass != null && this.form.pass != '' && this.form.pass != undefined){
              if (!reg1.test(this.form.pass)){
                this.$baseMessage('密码必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 6-20 之间', 'error');
                return;
              }
            }
          }

          if (this.form.id != null && this.form.id != '' && this.form.id != undefined){
            if (this.form.newPassword != null && this.form.newPassword != '' && this.form.newPassword != undefined){
              if (this.form.newPassword.length < 6){
                this.$baseMessage('请输入6位数以上的密码', 'error')
                return;
              }
            }

          }else {

            if (this.form.pass != null && this.form.pass != '' && this.form.pass != undefined){
              if (this.form.pass.length < 6){
                this.$baseMessage('请输入6位数以上的密码', 'error')
                return;
              }
            }
          }

          var phone  = this.form.phone
          if (phone != null && phone != undefined && phone != ''){
            var rex = new RegExp("^\\d+$")
            if(!rex.test(phone)){
              this.$baseMessage('请输入正确手机号', 'error')
              return ;
            }
          }

            this.$refs['form'].validate(async (valid) => {
                if (valid) {
                    this.loading = true
                    this.disabled = true
                    this.timer = setTimeout(() => {

                        setTimeout(() => {
                          this.loading = false
                          this.disabled = false
                        }, 400)

                        doEdit(this.form).then((res) => {
                          // this.loading = false;
                          // this.disabled = false;
                            if (res.code == 0) {
                                this.$baseMessage(res.msg, 'success')
                                this.$emit('fetch-data');
                                this.close()
                            } else {
                                this.$baseMessage(res.msg, 'error')
                            }
                        })
                    }, 2000)
                } else {
                    return false
                }
            })
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep{
  .labelEsp{
    .el-form-item__label{
      line-height:16px;
    }
  }
}
</style>
